﻿using System;
using System.Data;
using System.Web.Script.Services;
using System.Web.Services;
using Webapp;
using EnumKeys;
using System.Collections.Generic;
using System.Web;
namespace xundh.API.CM
{
    /// <summary>
    ///CM_Items 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class CM_Buy_Items : BaseService
    {
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Add(int CMId, string CMNumber, string CustomerName, string CustomerTel, string CustomerPersonID, int SignUserId,
            string SignUser, int SignDepartId, int PayType, int ChargePayType, decimal ChargeCustomer, decimal ChargeHouse,
              string PlanRebackBank, string PlanTransfer,
            string PlanBankPay, decimal FirstPayment, bool IsLimitBuy, bool IsLimitLoan,
            string Mem, int HouseId, string HouseCustomerName, string GetPropertyDate,
             decimal TotalPrice, int SellRegionArea, decimal HouseArea, string HouseTel, string HousePersonID, int CustomerId
            )
        {
            //todo:权限处理
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            xundh.BLL.CM_Buy_Items bll = new xundh.BLL.CM_Buy_Items();

            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "增")) return ServiceStateKeys.NoPermiss;
            //是否已存在
            List<xundh.Model.CM_Buy_Items> ms = bll.GetModelList("CMNumber='" + CMNumber + "'");

            ///参数处理
            CMNumber = StringUtil.CutBadSqlInfo(CMNumber);
            CustomerName = StringUtil.CutBadSqlInfo(CustomerName);
            CustomerTel = StringUtil.CutBadSqlInfo(CustomerTel);
            CustomerPersonID = StringUtil.CutBadSqlInfo(CustomerPersonID);
            HouseCustomerName = StringUtil.CutBadSqlInfo(HouseCustomerName);
            SignUser = StringUtil.CutBadSqlInfo(SignUser);
            Mem = StringUtil.CutBadSqlInfo(Mem);
            HouseTel = StringUtil.CutBadSqlInfo(HouseTel);
            HousePersonID = StringUtil.CutBadSqlInfo(HousePersonID);

            xundh.Model.CM_Buy_Items m;
            if (CMId > 0)
            {

                m = bll.GetModel(CMId);
            }
            else
            {
                if (ms.Count > 0)
                    return ServiceStateKeys.Exists;
                else
                {
                    m = new xundh.Model.CM_Buy_Items();
                    m.AddUser = U.UserName;
                    m.AddDepartId = U.DepartId;
                    m.AddTime = NOW;
                    m.AddIp = IP;
                    m.AddUserId = U.UserId;
                    m.NowStepInt = 0;
                    m.State = 0;
                }
            }

            m.CustomerName = CustomerName;
            m.CustomerTel = CustomerTel;
            m.CustomerPersonID = CustomerPersonID;
            m.SignUserId = SignUserId;
            m.SignUser = SignUser;
            m.SignDepartId = SignDepartId;
            m.ChargeTotal = ChargeCustomer + ChargeHouse;
            m.ChargeCustomer = ChargeCustomer;
            m.ChargeHouse = ChargeHouse;
            m.PayType = PayType;
            m.ChargePayType = ChargePayType;
            m.FirstPayment = FirstPayment;
            m.IsLimitBuy = IsLimitBuy;
            m.IsLimitLoan = IsLimitLoan ? 1 : 0;
            m.HouseId = HouseId;
            m.TotalPrice = TotalPrice;
            m.HouseArea = HouseArea;
            m.HouseRegionArea = SellRegionArea;
            m.HouseTel = HouseTel;
            m.HousePersonID = HousePersonID;
            m.HouseCustomerName = HouseCustomerName;
            m.CustomerId = CustomerId;
            m.CMNumber = CMNumber;

            if (StringUtil.isDate(PlanRebackBank)) m.PlanRebackBank = DateTime.Parse(PlanRebackBank);
            if (StringUtil.isDate(PlanTransfer)) m.PlanTransfer = DateTime.Parse(PlanTransfer);
            if (StringUtil.isDate(PlanBankPay)) m.PlanBankPay = DateTime.Parse(PlanBankPay);
            m.Mem = Mem;
            m.LastUserId = U.UserId;
            m.LastUser = U.UserName;
            m.LastDepartId = U.DepartId;
            m.LastTime = NOW;
            m.LastIp = IP;
            m.DocNowUser = "";
            m.DocNowUserId = 0;
            if (StringUtil.isDate(GetPropertyDate)) m.GetPropertyDate = DateTime.Parse(GetPropertyDate);
            xundh.Model.House_Sells mHouse = new Model.House_Sells();
            House.House_Sells houseService = new House.House_Sells();
            mHouse.State = (int)HouseState.SelfCopSold;
            houseService.UpdateStateForCM(HouseId, mHouse.State);
            if (CMId > 0)
                bll.Update(m);
            else
                bll.Add(m);
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true, Description = "更新合同状态，如果到最后一步，就更新合同状态")]
        public ServiceStateKeys UpdateStep(int CMId, int Step)
        {
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            ///参数处理
            xundh.BLL.CM_Buy_Items bll = new BLL.CM_Buy_Items();
            xundh.Model.CM_Buy_Items m = bll.GetModel(CMId);
            if (m == null) return ServiceStateKeys.NotExists;
            //todo:权限处理
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "改")) return ServiceStateKeys.NoPermiss;

            m.NowStepInt = Step;
            API.CM.CM_Buy_Steps serviceCMBuySteps = new CM_Buy_Steps();
            if (Step == serviceCMBuySteps.GetMaxStepId())
            {
                m.State = (int)CMState.Finish;
            }
            else
                m.State = (int)CMState.Normal;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetGraph(int year, int month)
        {
            string begin = year + "-" + month + "-1";
            DateTime endDate = DateTime.Parse(begin).AddMonths(1).AddDays(-1);
            string end = year + "-" + month + "-" + endDate.Day + " 23:59:59";

            string sql = "select top 6 SUM(ChargeTotal) as s,SignUser  from CM_Buy_Items " +
                "where AddTime between '" + begin + "' and '" + end + "'" +
                "group by ChargeTotal ,SignUser";
            xundh.BLL.BasePager bllP = new BLL.BasePager();
            using (DataSet ds = bllP.GetGPager(sql))
            {
                return new JsonTable(ds.Tables[0], ds.Tables[0].Rows.Count);
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows)
        {
            //todo:权限处理
            if (U == null) return null;
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (SystemGetBool("CM", "CMShowList"))
            {
                if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查"))
                    return null;
            }
            int DepartId = StringUtil.GetIntValue(REQUEST["SignDepartId"]);
            int SignUserId = StringUtil.GetIntValue(REQUEST["SignUserId"]);
            string CMNumber = StringUtil.GetNullToString(StringUtil.CutBadSqlInfo(REQUEST["CMNumber"]));
            int CM_SellBuildingId = StringUtil.Get_1Value(HttpContext.Current.Request["CM_SellBuildingId"]);

            string BuildingNames = "";
            if (CM_SellBuildingId == -1)
            {
                //文字搜索
                Region.Region_Buildings serviceRegionBuilding = new Region.Region_Buildings();
                string name = StringUtil.CutBadSqlInfo(StringUtil.GetNullToString(HttpContext.Current.Request["CM_SellBuildingId"]));
                if (name != "")
                {
                    BuildingNames = name;
                }
            }

            xundh.BLL.BasePager bll = new BLL.BasePager();
            string where = " 1=1 ";

            if (serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查所有"))
            {
                if (DepartId > 1)
                    where += " AND SignDepartId=" + DepartId;
                if (SignUserId > 0)
                    where += " AND SignUserId=" + SignUserId;
                if (CMNumber != "")
                    where += " AND CMNumber='" + CMNumber + "'";
            }
            else if (serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查部门"))
            {
                where += " AND SignDepartId=" + U.DepartId;
                if (SignUserId > 0)
                    where += " AND SignUserId=" + SignUserId;
                if (CMNumber != "")
                    where += " AND CMNumber='" + CMNumber + "'";
            }
            else if (SignUserId == U.UserId || SignUserId == U.AddUserId)
            {
                where += " AND SignUserId=" + SignUserId;
                if (CMNumber != "")
                    where += " AND CMNumber='" + CMNumber + "'";
            }
            else
            {
                return null;
            }
            if (CM_SellBuildingId > -1) where += " AND BuildingId=" + CM_SellBuildingId;
            if (BuildingNames != "") where += " AND BuildingName LIKE '%" + BuildingNames + "%'";
            string table = "v_CM_Houses";
            if (!U.UserAdmin)
            {
                where += " AND State <>" + 2;
            }

            JqGridHandler datagrid = new JqGridHandler(where);
            int recordcount = bll.GetAllCount(datagrid.StrWhere, table);

            string cols = "CMId,CMNumber,BuildingName,CustomerId,CustomerName,CustomerTel,CustomerPersonID,SignUserId,SignUser,SignDepartId,PayType,ChargeTotal,ChargeHouse,ChargeCustomer,ChargePayType,PlanRebackBank,HouseId,PlanTransfer,PlanBankPay,FirstPayment,IsLimitBuy,NowStepInt,State,Title,Mem,AddUserId,AddUser,AddDepartId,GetPropertyDate,AddTime,AddIp,LastUserId,LastUser,LastDepartId,LastTime,LastIp,TotalPrice,HouseRegionArea,HouseArea,HouseTel,HouseCustomerName,HousePersonID,HouseAddUser";
            datagrid.init(datagrid.StrWhere, page, recordcount, rows, "", "");
            if (datagrid.Order == "") datagrid.Order = "CMId DESC";
            using (DataSet ds = bll.GetPager(datagrid.Pagesize, datagrid.P, datagrid.StrWhere, datagrid.Order, table, cols))
            {
                return new JsonTable(ds.Tables[0], recordcount, datagrid.P, datagrid.Recordcount);
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public xundh.Model.CM_Buy_Items Query(int id)
        {
            if (U == null) return null;
            //todo:权限处理
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查"))
            {
                //没有查看权限
                return null;
            }
            xundh.BLL.CM_Buy_Items bll = new xundh.BLL.CM_Buy_Items();
            xundh.Model.CM_Buy_Items m = bll.GetModel(id);
            bool hasLimit = false;
            if (m.AddUserId == U.UserId || m.SignUserId == U.UserId)
                hasLimit = true;
            else if (m.SignDepartId == U.DepartId || m.AddDepartId == U.DepartId)
            {
                //有没有查看权限
                if (serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查部门"))
                {
                    hasLimit = true;
                }
            }
            else
            {
                if (serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "查所有"))
                {
                    hasLimit = true;
                }
            }
            if (!hasLimit) return null;
            return m;
        }
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys UpdateState(int id, int State)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.BLL.CM_Buy_Items bll = new xundh.BLL.CM_Buy_Items();
            xundh.Model.CM_Buy_Items m = bll.GetModel(id);
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "买卖合同", "改")) return ServiceStateKeys.NoPermiss;

            m.State = State;// (int)CMState.Stop;
            m.LastDepartId = U.DepartId;
            m.LastIp = IP;
            m.LastTime = NOW;
            m.LastUser = U.UserName;
            m.LastUserId = U.UserId;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        public ServiceStateKeys UpdateDocPosition(int id, int UserId, string UserName)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.BLL.CM_Buy_Items bll = new xundh.BLL.CM_Buy_Items();
            xundh.Model.CM_Buy_Items m = bll.GetModel(id);
            //权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            m.DocNowUserId = UserId;
            m.DocNowUser = UserName;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
    }
}
public enum CMState { NotStart, Normal, Stop, Finish }